package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.AccountingRecordDTO;
import com.api.shopapi.entity.dto.BusinessDTO;
import com.api.shopapi.entity.dto.OrderBusinessDTO;
import com.api.shopapi.entity.dto.UserDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 商家的结算记录
 * */

@RestController
@RequestMapping("AccountingRecord")
public class AccountingRecordController extends BaseController{

    @Autowired
    @Qualifier("AccountingRecordServiceImplOne")
    private AccountingRecordService accountingRecordService;

    @Autowired
    @Qualifier("BusinessStaffRelServiceImplOne")
    private BusinessStaffRelService businessStaffRelService;

    @Autowired
    @Qualifier("OrderBusinessServiceImplOne")
    private OrderBusinessService orderBusinessService;

    @Autowired
    @Qualifier("BusinessServiceImplOne")
    private BusinessService businessService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    @RequestMapping(value = "Page", method = RequestMethod.POST)
    public MyResult Page(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getIntValue("pageIndex");
            int pageSize = jsonObject.getIntValue("pageSize");
            String startTime = jsonObject.getString("startTime");
            String endTime = jsonObject.getString("endTime");
            int status = jsonObject.getInteger("status");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/AccountingRecord/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            BusinessStaffRel businessStaffRel = businessStaffRelService.getByStaffCode(staffCode);
            PageInfo<AccountingRecordDTO> accountingRecordPageInfo = accountingRecordService.getPage(pageIndex, pageSize, businessStaffRel.getBusinessCode(),startTime,endTime,status);

            return success(accountingRecordPageInfo);
        } catch (Exception e) {
            insertError("/AccountingRecord/Page",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "TransferAccounts", method = RequestMethod.POST)
    public MyResult TransferAccounts(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String accountingRecordCode = jsonObject.getString("accountingRecordCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/AccountingRecord/TransferAccounts");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            AccountingRecord byAccountingRecordCode = accountingRecordService.getByAccountingRecordCode(accountingRecordCode);
            byAccountingRecordCode.setStatus(2);
            accountingRecordService.update(byAccountingRecordCode);
            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/AccountingRecord/TransferAccounts",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "PageAll", method = RequestMethod.POST)
    public MyResult PageAll(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getIntValue("pageIndex");
            int pageSize = jsonObject.getIntValue("pageSize");
            String startTime = jsonObject.getString("startTime");
            String endTime = jsonObject.getString("endTime");
            int status = jsonObject.getInteger("status");
            String businessCode = jsonObject.getString("businessCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/AccountingRecord/PageAll");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            PageInfo<AccountingRecordDTO> accountingRecordPageInfo = accountingRecordService.getPage(pageIndex, pageSize, businessCode,startTime,endTime,status);
            List<AccountingRecordDTO> AccountingRecordDTOList = accountingRecordPageInfo.getList();
            for (AccountingRecordDTO accountingRecordDTO : AccountingRecordDTOList) {
                Business byBusinessCode = businessService.getByBusinessCode(accountingRecordDTO.getBusinessCode());
                BusinessDTO businessDTO = mapper.map(byBusinessCode,BusinessDTO.class);
                User user = userService.getByUserCode(businessDTO.getUserCode());
                if(user!=null){
                    UserDTO userDTO = mapper.map(user,UserDTO.class);
                    businessDTO.setUserDTO(userDTO);
                    businessDTO.setBusinessName(userDTO.getName());
                    accountingRecordDTO.setBusinessDTO(businessDTO);
                }
            }
            return success(accountingRecordPageInfo);
        } catch (Exception e) {
            insertError("/AccountingRecord/PageAll",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "UpdateOrderBusinessStatus", method = RequestMethod.GET)
    public String updateOrderBusinessStatus() {
        orderBusinessService.updateOrderBusinessStatus();
        return "OK!";
    }

    @RequestMapping(value = "UpdateOrderBusinessTime", method = RequestMethod.GET)
    public String updateOrderBusinessTime() {
        orderBusinessService.updateOrderBusinessTime();
        return "OK!";
    }

    @RequestMapping(value = "GetBusinessDayList", method = RequestMethod.GET)
    public String getBusinessDayList() {
        List<AccountingRecord> businessDayAllList = orderBusinessService.getBusinessDayAllList();
        for(AccountingRecord accountingRecord:businessDayAllList){
            accountingRecord.setAccountingRecordCode(UUID.randomUUID().toString());
            accountingRecord.setStatus(1);
            accountingRecordService.insert(accountingRecord);
        }
        return "OK!";
    }

    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void AutoAccounting() {
        try {
            List<Business> list = businessService.getList();
            if(list.size()>0){
                for (Business business :list){
                    User user = userService.getByUserCode(business.getUserCode());
                    if(user!=null){
                        Double businessDayMoney = orderBusinessService.getBusinessDayMoney(business.getBusinessCode(), 1);
                        if(businessDayMoney!=0.0){
                            AccountingRecord accountingRecord = new AccountingRecord();
                            accountingRecord.setAccountingRecordCode(UUID.randomUUID().toString());
                            accountingRecord.setBusinessCode(business.getBusinessCode());
                            accountingRecord.setPrice(businessDayMoney);
                            accountingRecord.setStatus(1);
                            Calendar calendar = Calendar.getInstance();
                            calendar.add(Calendar.DATE, -1);
                            accountingRecord.setCreateTime(calendar.getTime());
                            accountingRecordService.insert(accountingRecord);
                        }
                    }
                }
            }else {
                insertError("/AccountingRecord/AutoAccounting","","未查到商家","api");
            }
        } catch (Exception e) {
            insertErrorForAffair("/AccountingRecord/AutoAccounting!",new JSONObject(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

}
